<script setup>
import { ref, onMounted } from 'vue'
import {
  getAllQuestionInfoAPI,
  disableQuestionAPI,
  enableQuestionAPI
} from '@/api/user'

const allQuestionInfo = ref([])
const getAllQuestionInfo = async () => {
  const res = await getAllQuestionInfoAPI()
  allQuestionInfo.value = res.data
  if (allQuestionInfo.value.length > pageSize.value) {
    nowPageInfo.value = allQuestionInfo.value.slice(index.value, end.value)
  } else {
    nowPageInfo.value = allQuestionInfo.value
  }
}

const disableQuestion = async (problem) => {
  const res = await disableQuestionAPI(problem)
  if (res.data == 1) {
    ElMessage.success('禁用成功')
    getAllQuestionInfo()
  } else {
    ElMessage.error('禁用失败')
  }
}
const enableQuestion = async (problem) => {
  const res = await enableQuestionAPI(problem)
  if (res.data == 1) {
    ElMessage.success('禁用成功')
    getAllQuestionInfo()
  } else {
    ElMessage.error('禁用失败')
  }
}

onMounted(() => {
  getAllQuestionInfo()
})

const currentPage = ref(1)
const pageSize = ref(10)
const index = ref((currentPage.value - 1) * pageSize.value)
const end = ref(index.value + pageSize.value)
const nowPageInfo = ref([])
const handleSizeChange = (val) => {
  pageSize.value = val
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value = val
  index.value = (currentPage.value - 1) * pageSize.value
  end.value = index.value + pageSize.value
  console.log(index.value, end.value)
  nowPageInfo.value = allQuestionInfo.value.slice(index.value, end.value)
}
</script>

<template>
  <el-table :data="nowPageInfo" border style="width: 100%">
    <el-table-column prop="Id" label="id" visable="false" width="50" />
    <el-table-column prop="ProblemName" label="问题" width="360" />
    <el-table-column prop="Tag" label="标签" />
    <el-table-column prop="Money" label="悬赏金额">
      <template v-slot:default="{ row }">
        <span v-if="row.Money === 0" class="money">非悬赏</span>
        <span v-else class="money">{{ row.Money + '元' }}</span>
      </template>
    </el-table-column>

    <el-table-column prop="UserName" label="发布人" />

    <el-table-column label="操作" width="200">
      <template #default="scope">
        <!-- 根据 Status 的值显示不同的按钮 -->
        <el-button
          type="danger"
          v-if="scope.row.Status === 1"
          @click="disableQuestion(scope.row)"
          >封禁</el-button
        >
        <el-button type="success" v-else @click="enableQuestion(scope.row)"
          >解封</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[100, 200, 300, 400]"
    layout="sizes, prev, pager, next"
    :total="allQuestionInfo.length"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    background
    style="margin: 10px auto"
  />
</template>
<style>
.money {
  font-weight: 900;
}
</style>
